package leetcode.tanxin;

import java.util.Arrays;
import java.util.Comparator;

/**
 给定一个区间的集合，找到需要移除区间的最小数量，使剩余区间互不重叠。
 输入: [ [1,2], [2,3], [3,4], [1,3] ]

 输出: 1

 解释: 移除 [1,3] 后，剩下的区间没有重叠。
 */
public class EraseOverlapIntervals435 {
    public static void main(String[] args) {
//            int [][] arr = new int[][]{{1,2},{2,3},{3,4},{1,3}};
            int [][] arr = new int[][]{{1,2},{2,3}};
        int res = eraseOverlapIntervals(arr);
        System.out.println(res);
    }

    public static  int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o2[1]!=o1[1])
                    return o1[1]-o2[1];
                else
                    return o1[0]-o2[0];
            }
        });

        int lastEnd = intervals[0][1];
        int count = 0;

        for (int i = 1; i < intervals.length; i++) {
            int [] inter = intervals[i];
            if(inter[0]<lastEnd)//开始的小于上一个结尾的
                count++;
            else
                lastEnd = inter[1];
        }
        return  count;
    }

}